#ifndef __THREAD_HPP__
#define __THREAD_HPP__
#include <iostream>
#include <unistd.h>
#include <string>
#include <pthread.h>
#include <functional>
using namespace std;

namespace yss
{
    template <class T>
    using func_t = function<void(T&)>;

    template <class T>
    class Thread
    {
    public:
        void Excute()
        {
            _func(_data);
        }
        Thread(func_t<T> func, T &data, const string &name = "none-name")
            :_func(func), _data(data), _threadname(name), _stop(true)
        {
        }
        static void* runthread(void* args)//类成员函数，形参有this指针
        {
            Thread<T>* self = static_cast<Thread<T>*>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, runthread, this);
            if(!n)
            {
                _stop = false;
                return true;
            }
            else 
            {
                return false;
            }
        }
        void Detach()
        {
            if(!_stop)
            {
                pthread_detach(_tid);
            }
        }
        void Join()
        {
            if(!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }
        void Stop()
        {
            _stop = true;
        }
        string getName()
        {
            return _threadname;
        }
        ~Thread()
        {}
    private:
        pthread_t _tid;
        string _threadname;
        bool _stop;
        func_t<T> _func;
        T& _data;
        //T& _data;
        //T _data;
    };
}

#endif